<template>
  <div>
    <div class="comment-post">
      <div class="avatar">
        <span>{{ user.name[0].toUpperCase() }}</span>
      </div>
      <div class="comment-content-box editing">
        <textarea
          class="comment-content-input"
          placeholder="添加评论……"
          ref="inputComment"
          v-model="newComment"
        ></textarea>
        <button class="btn btn-edit" @click="postNewComment">保存</button>
      </div>
    </div>

    <ul class="comments" v-if="comments.rows">
      <li class="comment" v-for="comment of comments.rows" :key="comment.id">
        <div class="avatar">
          <span>{{ comment.user.name[0].toUpperCase() }}</span>
        </div>
        <div class="description">
          <div class="header">
            <strong>{{ comment.user.name }} </strong>
            <span>at</span>
            <i> {{ comment.createdAt | formatTime }}</i>
          </div>
          <div class="content">{{ comment.content }}</div>
        </div>
      </li>
    </ul>

    <div class="comment-pagination">
      <Pagination
        :pages="comments.pages"
        :page="comments.page"
        @changePage="changePage"
      ></Pagination>
    </div>
  </div>
</template>

<script>
import dateTime from "../../utils/dataTime";
import Pagination from "@/components/Pagination/pagination";

export default {
  name: "Comment",

  components: { Pagination },

  data() {
    return {
      comments: {},
      newComment: "",
    };
  },

  computed: {
    user() {
      return this.$store.state.user.info;
    },
  },

  filters: {
    formatTime: dateTime,
  },

  props: {
    cardId: {
      type: Number,
      required: true,
    },
  },

  async created() {
    await this.getComments();
  },

  methods: {
    async getComments(page = 1) {
      try {
        let { data } = await this.$store.dispatch("comment/getComments", {
          boardListCardId: this.cardId,
          page,
        });

        this.comments = data;
      } catch (e) {
        console.log(e);
      }
    },

    async postNewComment() {
      if (this.newComment.trim() !== "") {
        try {
          await this.$store.dispatch("comment/postComment", {
            boardListCardId: this.cardId,
            content: this.newComment,
          });
          await this.getComments();
          this.newComment = "";
          this.$message.success("添加留言成功");
        } catch (e) {
          console.log(e);
        }
      }
      this.$refs.inputComment.focus();
    },

    async changePage(page) {
      await this.getComments(page);
    },
  },
};
</script>

<style>
</style>